<template>
  <div>
    <el-card class="login" shadow="always" :body-style="{ padding: '20px' }">
      <div slot="header">
        <span>请登录</span>
      </div>
      <!-- card body -->
      <el-form
        :model="form"
        ref="loginRef"
        :rules="rules"
        label-width="80px"
        :inline="false"
        size="normal"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login" :loading="loading"
            >登录</el-button
          >
          <el-button class="el-btn">退出</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import { login } from '../api/login'
import { setToken } from '../utils/token'
export default {
  data: () => ({
    loading: false,
    form: {
      username: '',
      password: ''
    },
    rules: {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 3, max: 13, message: '长度在 3 到 13 个字符', trigger: 'blur' }
      ]
    }
  }),
  methods: {
    login() {
      this.$refs.loginRef.validate((valid) => {
        if (valid) {
          this.loading = true
          const { username, password } = this.form
          login({
            username: username.trim(),
            password: password
          })
            .then((res) => {
              // localStorage.token = res.data.token
              setToken(res.data.token)
              this.$message({
                message: '登录成功',
                type: 'success'
              })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error 888!!')
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.login {
  width: 25rem;
  margin: 150px auto;
  .el-form-item__label {
    padding: 0 35px 0 0;
  }
  .el-btn {
    margin-left: 100px;
  }
}
</style>